<template>
  <div class="">
    <el-dialog v-model="dialogFormVisible" title="个人信息" width="500" destroy-on-close :close-on-click-modal="closeOnClickModal">
      <el-form :model="form" label-width="auto" style="max-width: 600px">
        <el-form-item label="账号名">
          <el-input v-model="form.username" disabled/>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="form.phone" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="onSubmit">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
  import { reactive, ref } from 'vue'
  import { getItem, setItem } from '~/utils/localStorage'
  import { showMessage } from '~/utils/my-notification'
  import { ElMessageBox } from 'element-plus'
  import { updateUserInfo } from '~/api/acl/user'

  const dialogFormVisible = ref(false)
  const closeOnClickModal = ref(false)

  const form = reactive({
    id: 0,
    username: '',
    name: '',
    phone: ''
  })

  const userInfo = getItem('userinfo')
  function init() {
    dialogFormVisible.value = true
    if(!userInfo) {
      showMessage('请先登录!', 'warning')
      return
    }
    const data = userInfo.data
    form.id = data.id
    form.username = data.username
    form.name = data.name
    form.phone = data.phone
  }
  
  // 提交
  function onSubmit() {
    ElMessageBox.confirm(`确定进行提交操作?`, '提示',{
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      closeOnClickModal: false
    }).then(() => {
      updateUserInfo(form).then(res => {
        if(res && res.data.code === 200) {
          const data = userInfo.data
          data.name = form.name
          data.phone = form.phone
          userInfo.data = data
          setItem('userinfo', userInfo)
          dialogFormVisible.value = false
        } else {
          showMessage(res.data.message, 'error')
        }
      })
    }).catch(err => {
      console.log(err)
    })
  }

  // 将方法暴露给父组件
  defineExpose({
    init
  })
</script>
<style>
</style>
